package com.szosen.jkzj.activity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mjdev.libaums.UsbMassStorageDevice;
import com.github.mjdev.libaums.fs.FileSystem;
import com.github.mjdev.libaums.fs.UsbFile;
import com.github.mjdev.libaums.fs.UsbFileInputStream;
import com.github.mjdev.libaums.partition.Partition;
import com.lzy.okgo.callback.StringCallback;
import com.szosen.application.MyApplication;
import com.szosen.device.jianhuyi.BeneCheckDeviceHB;
import com.szosen.jkzj.R;
import com.szosen.json.Data_loginReturn;
import com.szosen.json.JsonUtil;
import com.szosen.json.Role;
import com.szosen.util.BackGroundThread;
import com.szosen.util.FileSaveUtil;
import com.szosen.util.SharedpreferenceUtil;
import com.szosen.util.StringUtils;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;
import com.szosen.web.UpdateTool;
import com.szosen.web.WebService;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.Response;

public class SettingActivity extends BaseActivity {
    private EditText et_name, et_password, et_name_new, et_password_new;
    private EditText et_server_govId, et_server_doctorId, et_hospitalName,
            et_service_password;
    private Button btn_edit, btn_login;
    private Context mContext;
    private TextView tv_version;
    private Button btn_checkUpdate;
    /**
     * 服务器名字
     */
    private String mServerName;
    /**
     * 服务器密码
     */
    private String mServerPassword;
    private EditText et_time;
    private Button btn_setTime, btn_updateJianhuyi, btn_updatejianhuyi_fromotg;
    private BeneCheckDeviceHB beneCheckDevice;
    private UsbManager myManager;
    private static final String ACTION_USB_PERMISSION = "com.wch.wchusbdriver.USB_PERMISSION";
    private Context context;
    private RadioButton rb_neiwang, rb_waiwang;
    // 显示选择登陆后的角色选择
    Spinner sp_role;
    List<String> sp_datas;
    ArrayAdapter mSp_adapter;
    private TextView tv_jianhuyi_version;
    //服务器地址
    private EditText et_serverAddress;
    boolean isFromOTG = false;// 是从u盘更新还是网络更新， true u盘 ，false网络
    public LinkedHashMap<String, String> mRoleMap = new LinkedHashMap<String, String>();
    /***
     * 下位机升级取消的标记
     */
    private boolean isCancel_uploadXiaweiji = false;
    /***
     * 下位机的固件的名字。
     */
    private final String fileName_xiaweijigujian = "ASUPD.AS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        super.setTitleContent("【设置】");
        mContext = this;
        initView();
        getVersion();
    }

    private void getVersion() {
        String version = Tools.getVersionCode(context);
        tv_version.setText("版本号：" + version);
        myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        beneCheckDevice = new BeneCheckDeviceHB(myManager,
                SettingActivity.this, ACTION_USB_PERMISSION, usbHandler);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (beneCheckDevice != null && beneCheckDevice.isConnected()) {
                    // 查询版本号
                    byte[] command = new byte[]{(byte) 0xEE, 0x35,
                            (byte) 0xf0, 0x00, (byte) 0x00, 0X55, (byte) 0XCC};
                    beneCheckDevice.WriteData(command, command.length, 2000);
                    System.out.println("发送了查询版本号的命令getVersion");
                }
            }
        }).start();
    }

    /***
     * 跳转到高级设置中，备份还原软件数据
     * @param view
     */
    public void toAdvancedSetting(View view) {
        Intent intent = new Intent(this, AdvancedSettingActivity.class);
        startActivity(intent);
    }

    private final int what_downAPK = 11;
    private final int what_downAPK_failed = 44;
    private final int what_showDialog_updateXiaweiji = 22;
    private final int what_showDialog_updateXiaweijinoneed = 33;
    private final int what_uploadXiaweiji = 55;
    private final int what_downxiaweiji_error = 88;
    private final int what_showDialog_updateapknoneed = 77;
    private final int what_downloadXiaweijiFile = 66;
    private final int what_showDialogCancle = 99;

    private void dismissDialog() {
        if (mUpdateXiaweijiDialog != null && mUpdateXiaweijiDialog.isShowing()) {
            mUpdateXiaweijiDialog.dismiss();
        }
    }

    private DownloadTask downloadTask;
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 666:
                    String[] s = (String[]) msg.obj;
                    ToastTool.showLong(context, "当前版本是:" + s[0] + "\n服务器版本是："
                            + s[1]);
                    break;
                case what_downxiaweiji_error:
                    dismissDialog();
                    mUpdateXiaweijiDialog = showDialog("提示", "下载文件发生错误!", true);
                    mUpdateXiaweijiDialog.show();
                    break;
                case what_downAPK:
                    String fileUrl = (String) msg.obj;
                    downloadTask = new DownloadTask(SettingActivity.this);
                    downloadTask.execute(fileUrl, FileSaveUtil.getSDCardPath()
                            + "/chaozhou.apk");
                    break;
                case what_downAPK_failed:
                    dismissDialog();
                    mUpdateXiaweijiDialog = showDialog("提示", "获取更新信息失败!", true);
                    mUpdateXiaweijiDialog.show();
                    // ToastTool.showLong(context, "获取更新信息失败！");
                    // ToastTool.showLong(context, "获取更新信息失败！");
                    break;
                case what_showDialog_updateXiaweiji:
                    dismissDialog();
                    // 设置不能有一个取消的按钮。
                    mUpdateXiaweijiDialog = showDialog("提示",
                            "正在升级下位机，请确保下位机电量充足，请耐心等待!\n请勿拔掉数据线，更新成功后重启下位机", true);
                    mUpdateXiaweijiDialog.show();
                    break;
                case what_showDialog_updateXiaweijinoneed:
                    dismissDialog();
                    mUpdateXiaweijiDialog = showDialog("提示", "下位机已是最新版本，无需升级!",
                            true);
                    mUpdateXiaweijiDialog.show();
                    break;
                case what_showDialog_updateapknoneed:
                    dismissDialog();
                    mUpdateXiaweijiDialog = showDialog("提示", "软件已是最新版本，无需升级!", true);
                    mUpdateXiaweijiDialog.show();
                    break;
                case what_downloadXiaweijiFile:
                    // 根据文件下载url来下载固件包
                    String fileXiaweijiUrl = (String) msg.obj;
                    downloadTask = new DownloadTask(SettingActivity.this);
                    downloadTask.execute(fileXiaweijiUrl,
                            FileSaveUtil.getSDCardPath() + "/"
                                    + fileName_xiaweijigujian);
                    break;
                case what_showDialogCancle:
                    dismissDialog();
                case what_uploadXiaweiji:
                    // 发送命令开始更新一体机
                    if (isCancel_uploadXiaweiji) {
                        isCancel_uploadXiaweiji = false;
                        return;
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (beneCheckDevice != null
                                    && beneCheckDevice.isConnected()) {
                                // 写入开始更新的命令。
                                byte[] command = new byte[]{(byte) 0xEE, 0x35,
                                        (byte) 0xff, 0x55, (byte) 0xaa, 0X55,
                                        (byte) 0XCC};
                                // 查询版本号
                                // byte[] command = new byte[] { (byte) 0xEE, 0x35,
                                // (byte) 0xf0, 0x00, (byte) 0x00, 0X55,
                                // (byte) 0XCC };
                                beneCheckDevice.WriteData(command, command.length,
                                        2000);
                            }
                        }
                    }).start();
                    break;
                default:
                    break;
            }
        }
    };

    private String path = "潮州版";

    // 比对下服务器的版本和本地的版本信息，然后下载软件，下载固件后，发命令升级一体机。

    /***
     * 版本号为V00000.00一共
     *
     * @param currentVersion
     * @param webVersion
     */
    private boolean checkXiaWeijiVersion(String currentVersion,
                                         String webVersion) {
        mHandler.obtainMessage(666, new String[]{currentVersion, webVersion})
                .sendToTarget();
        if (TextUtils.isEmpty(currentVersion) || TextUtils.isEmpty(webVersion)) {
            return false;
        }
        String[] currentVersions = currentVersion.split("\\.");
        String[] webVersions = webVersion.split("\\.");
        if (currentVersions == null || currentVersions.length < 2
                || webVersions == null || webVersions.length < 2) {
            return false;
        }
        String current0 = currentVersions[0];
        String current1 = currentVersions[1];
        String web0 = webVersions[0];
        String web1 = webVersions[1];
        if (current0.length() != 6 || web0.length() != 6
                || current1.length() != 2 || web1.length() != 2) {
            return false;
        }
        if (current0.substring(1, 2).equals(web0.substring(1, 2))
                || web0.substring(1, 2).toUpperCase().equals("X")
                || current0.substring(1, 2).toUpperCase().equals("X")) {
            if (current0.substring(2, 3).equals(web0.substring(2, 3))
                    || web0.substring(2, 3).toUpperCase().equals("X")
                    || current0.substring(2, 3).toUpperCase().equals("X")) {
                if (current0.substring(3, 4).equals(web0.substring(3, 4))
                        || web0.substring(3, 4).toUpperCase().equals("X")
                        || current0.substring(3, 4).toUpperCase().equals("X")) {
                    if (current0.substring(5, 6).equals(web0.substring(5, 6))
                            || web0.substring(5, 6).toUpperCase().equals("X")
                            || current0.substring(5, 6).toUpperCase()
                            .equals("X")) {
                        if (current0.substring(1, 2).equals(
                                web0.substring(1, 2))
                                || web0.substring(1, 2).toUpperCase()
                                .equals("X")
                                || current0.substring(1, 2).toUpperCase()
                                .equals("X")) {
                            try {
                                int currentInt = Integer.parseInt(current1);
                                int webInt = Integer.parseInt(web1);
                                if (currentInt < webInt) {
                                    return true;
                                } else {
                                    return false;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                return false;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    public void checkXiaweijiUpdate() {
        if (!Tools.isNetConnected(context)) {
            ToastTool.showShort(context, "请检查网络连接！");
            return;
        }
        try {
            new BackGroundThread(new BackGroundThread.BackGroundTask() {
                @Override
                public void process() {
                    try {
                        // 检查是否需要更新的按钮。
                        // 从后台获取txt文件
                        File updateFile = UpdateTool.getUpdateXiaweijiMessage();
                        if (updateFile == null) {
                            mHandler.obtainMessage(what_downAPK_failed)
                                    .sendToTarget();
                            return;
                        }
                        InputStreamReader inputStreamReader = null;
                        inputStreamReader = new InputStreamReader(
                                new FileInputStream(updateFile), "gbk");
                        BufferedReader reader = new BufferedReader(
                                inputStreamReader);
                        String line;
                        boolean needUpdate = false;
                        while ((line = reader.readLine()) != null) {
                            // System.out.println("获取的更新文件txt的行：" + line);
                            if (line.contains("&&")) {
                                String version = xiaweiji_version;
                                String[] upDateMessage = line.split("&&");
                                if (upDateMessage != null
                                        && upDateMessage.length == 2) {
                                    // 测试的。先固定一个。和服务的对比下。
                                    // version = "V00011.01";
                                    // V011XX.02
                                    if (checkXiaWeijiVersion(version,
                                            upDateMessage[0])) {
                                        String fileUrl = upDateMessage[1];
                                        // 打开此url
                                        // UpdateTool.openURlByBrower(
                                        // SettingActivity.this,
                                        // fileUrl);
                                        // execute this when the
                                        // downloader must be fired
                                        // 发送一个url。来下载固件包
                                        mHandler.obtainMessage(
                                                what_downloadXiaweijiFile,
                                                fileUrl).sendToTarget();
                                        needUpdate = true;
                                        return;
                                    }
                                    // else {
                                    // mHandler.obtainMessage(
                                    // what_showDialog_updateXiaweijinoneed)
                                    // .sendToTarget();
                                    // // return;
                                    // }
                                }
                            }
                        }
                        if (!needUpdate) {
                            mHandler.obtainMessage(
                                    what_showDialog_updateXiaweijinoneed)
                                    .sendToTarget();
                            return;
                        }
                        // // 发送更新信息
                        // mHandler.obtainMessage(what_downAPK_failed)
                        // .sendToTarget();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void checkUpdate(View view) {
        if (!Tools.isNetConnected(context)) {
            ToastTool.showShort(context, "请检查网络连接！");
            return;
        }
        mUpdateXiaweijiDialog = showDialog("提示", "正在获取软件的更新信息!", true);
        mUpdateXiaweijiDialog.show();
        try {
            new BackGroundThread(new BackGroundThread.BackGroundTask() {
                @Override
                public void process() {
                    try {
                        // 检查是否需要更新的按钮。
                        // 从后台获取txt文件
                        File updateFile = UpdateTool.getUpdateMessage();
                        if (updateFile == null) {
                            mHandler.obtainMessage(what_downAPK_failed)
                                    .sendToTarget();
                            return;
                        }
                        InputStreamReader inputStreamReader = null;
                        inputStreamReader = new InputStreamReader(
                                new FileInputStream(updateFile), "gbk");
                        BufferedReader reader = new BufferedReader(
                                inputStreamReader);
                        String line;
                        while ((line = reader.readLine()) != null) {
                            System.out.println("获取的更新文件txt的行：" + line);
                            if (line.contains("&&")) {
                                String version = Tools.getVersionCode(context);
                                String[] upDateMessage = line.split("&&");
                                if (upDateMessage != null
                                        && upDateMessage.length == 2) {
                                    String[] banben1 = upDateMessage[0]
                                            .split("\\.");
                                    String[] currentVersions = version
                                            .split("\\.");
                                    if (currentVersions != null
                                            && banben1 != null
                                            && currentVersions.length == 2
                                            && banben1.length == 2) {
                                        // 切割出来的V0000000.0001 比对.的前面的内容。
                                        if (currentVersions[0]
                                                .equals(banben1[0])) {
                                            int currentVersion = Integer
                                                    .valueOf(currentVersions[1]);
                                            int lastestVersion = Integer
                                                    .valueOf(banben1[1]);
                                            if (lastestVersion > currentVersion) {
                                                // 获取&&的后缀名：chaozhou.apk，如：V0000000.0001&&chaozhou.apk
                                                String fileUrl = upDateMessage[1];
                                                // 打开此url
                                                // UpdateTool.openURlByBrower(
                                                // SettingActivity.this,
                                                // fileUrl);
                                                // execute this when the
                                                // downloader must be fired
                                                mHandler.obtainMessage(
                                                        what_downAPK, fileUrl)
                                                        .sendToTarget();
                                                return;
                                            } else {
                                                mHandler.obtainMessage(
                                                        what_showDialog_updateapknoneed)
                                                        .sendToTarget();
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        // 发送更新信息
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    private UsbMassStorageDevice[] storageDevices;

    public void readDeviceList() {
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this);
        System.out.println("usb设备storageDevices长度：" + storageDevices.length);
        for (UsbMassStorageDevice device : storageDevices) {
            System.out.println("usb设备名称getDeviceName："
                    + device.getUsbDevice().getDeviceName());
            if (device.getUsbDevice().getVendorId() != 1027
                    && device.getUsbDevice().getVendorId() != 4817
                    && device.getUsbDevice().getProductId() != 24577) {
                if (usbManager.hasPermission(device.getUsbDevice())) {
                    readDevice(device);
                } else {
                    PendingIntent pendingIntent = PendingIntent.getBroadcast(
                            this, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    usbManager.requestPermission(device.getUsbDevice(),
                            pendingIntent);
                }
            }
        }
    }

    private List<UsbFile> usbFiles = new ArrayList<UsbFile>();

    private void addFile2List(String deviceName) {// 添加文件和文件夹到gridView显示
        try {
            StringBuilder sb = new StringBuilder();
            for (UsbFile file : mUsbFile.listFiles()) {
                usbFiles.add(file);
                sb.append(file.getName() + "\n");
                String name = file.getName();
                if (!TextUtils.isEmpty(name) && name.equals("ASUPD")) {
                    // UsbFile ub = file.createFile("ASUPD.AS");
                    for (UsbFile fileSon : file.listFiles()) {
                        String name2 = fileSon.getName();
                        if (!TextUtils.isEmpty(name2)
                                && name2.equals("ASUPD.AS")) {
                            readFile(fileSon);
                            break;
                        }
                    }
                }
            }
            // ToastTool.showLong(mInstance,
            // "usbFiles.size="+usbFiles.size()+",名字="+usbFiles.get(0).getName()+"\n"+sb.toString());
            // Collections.sort(usbFiles, new Comparator<UsbFile>() {// 简单排序
            // 文件夹在前
            // // 文件在后
            // @Override
            // public int compare(UsbFile oFile1, UsbFile oFile2) {
            // if (oFile1.isDirectory())
            // return -1;
            // else
            // return 1;
            // }
            // });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ExecutorService executorService;

    private void readFile(final UsbFile uFile) {
        String sdPath = FileSaveUtil.getSDCardPath();// 获取sd根目录 创建一个同名文件
        String filePath = sdPath + uFile.getName();
        executorService = Executors.newCachedThreadPool();// 30大小的线程池
        final File f = new File(filePath);
        // if (f.exists()) {
        //
        // } else {
        try {
            f.createNewFile();
            // 设置视图
            // 执行线程
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileOutputStream os = new FileOutputStream(f);
                        InputStream is = new UsbFileInputStream(uFile);
                        redFileStream(os, is);
                        System.out.println("写入U盘文件完成");
                    } catch (final Exception e) {
                        e.printStackTrace();
                        FileSaveUtil.saveTxtFile("dd",
                                "executorServicelog.txt", e.getMessage());
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        // }
    }

    private void redFileStream(OutputStream os, InputStream is)
            throws IOException {
        /**
         * 写入文件到U盘同理 要获取到UsbFileOutputStream后 通过 f.createNewFile();调用 在U盘中创建文件
         * 然后获取os后 可以通过输出流将需要写入的文件写到流中即可完成写入操作
         */
        int bytesRead = 0;
        byte[] buffer = new byte[1024 * 8];
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
        os.close();
        is.close();
        // ToastTool.showLong(mInstance, "写完文件了");
    }

    UsbFile mUsbFile;

    private void readDevice(UsbMassStorageDevice device) {
        // before interacting with a device you need to call init()!
        try {
            device.init();
            // Only uses the first partition on the device
            Partition partition = device.getPartitions().get(0);
            FileSystem currentFs = partition.getFileSystem();
            // fileSystem.getVolumeLabel()
            // Log.d(TAG, "Capacity: " + currentFs.getCapacity());
            // Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());
            // Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());
            // Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());
            UsbFile root = currentFs.getRootDirectory();// 获取根目录
            String deviceName = currentFs.getVolumeLabel();// 获取设备标签
            mUsbFile = root;
            addFile2List(deviceName);// 添加文件
        } catch (Exception e) {
            e.printStackTrace();
            // ToastTool.showLong(mInstance,"出错了"+e.getMessage());
            FileSaveUtil.saveTxtFile("error", "log.txt", e.getMessage());
        }
    }

    public String getKeyByValue(Map<String, String> map, String value) {
        String key = "";
        Iterator i = map.entrySet().iterator();
        String temp;
        while (i.hasNext()) {
            Map.Entry entry = (Map.Entry) i.next();
            temp = entry.getValue().toString();
            if (value.equals(temp)) {
                key = entry.getKey().toString();
                return key;
            }
        }
        return key;
    }

    private void initView() {
        context = this;
        sp_role = (Spinner) findViewById(R.id.setting_sp_jigou);
        sp_datas = new ArrayList<String>();
        mSp_adapter = new ArrayAdapter<String>(this,
                R.layout.login_spinner_item, sp_datas);
        mSp_adapter.setDropDownViewResource(R.layout.login_spinner_item);
        sp_role.setAdapter(mSp_adapter);
        sp_role.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                // 获取下拉的卫生室的名称
                String item = (String) parent.getItemAtPosition(position);
                String token = getKeyByValue(mRoleMap, item);
                SharedpreferenceUtil.setToken(context, token);
                // SharedpreferenceUtil.setOnGovId(context, Manaunitid);
                // 存放token
                et_server_govId.setText(token);
                // 显示医院的名称并保存
                et_hospitalName.setText(item);
                SharedpreferenceUtil.setHospitalName(mContext, item);
                ToastTool.showLong(context, "登陆成功");
                MyApplication.setUserLogin(true);
                // jump2MainUi();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        et_serverAddress = (EditText) findViewById(R.id.setting_et_serverAddress);
        rb_neiwang = (RadioButton) findViewById(R.id.setting_rb_userWebNeiwang);
        rb_waiwang = (RadioButton) findViewById(R.id.setting_rb_userWebWaiwang);
        tv_jianhuyi_version = (TextView) findViewById(R.id.setting_tv_version_jianhuyi);
        String useWeb = SharedpreferenceUtil.getUseWeb(context,
                SharedpreferenceUtil.USE_WEB_NEIWANG);
        if (!TextUtils.isEmpty(useWeb)) {
            if (useWeb.equals(SharedpreferenceUtil.USE_WEB_NEIWANG)) {
                rb_neiwang.setChecked(true);
            } else if (useWeb.equals(SharedpreferenceUtil.USE_WEB_WAIWANG)) {
                rb_waiwang.setChecked(true);
            }
        }
        RadioGroup rb_userWeb = (RadioGroup) findViewById(R.id.setting_rg_userWeb);
        rb_userWeb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.setting_rb_userWebNeiwang) {
                    SharedpreferenceUtil.setUseWeb(context,
                            SharedpreferenceUtil.USE_WEB_NEIWANG);
                } else if (checkedId == R.id.setting_rb_userWebWaiwang) {
                    SharedpreferenceUtil.setUseWeb(context,
                            SharedpreferenceUtil.USE_WEB_WAIWANG);
                }
            }
        });
        RadioGroup setting_rg_xuetang = (RadioGroup) findViewById(R.id.setting_rg_xuetang);
        setting_rg_xuetang.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.setting_rb_xuetang_kenuo) {
                    SharedpreferenceUtil.setUseSannuo(context, false);
                } else if (checkedId == R.id.setting_rb_xuetang_sannuo) {
                    SharedpreferenceUtil.setUseSannuo(context, true);
                }
            }
        });
        tv_version = (TextView) findViewById(R.id.setting_tv_version);
        et_name = (EditText) findViewById(R.id.setting_et_name);
        et_password = (EditText) findViewById(R.id.setting_et_password);
        et_name_new = (EditText) findViewById(R.id.setting_et_nameNew);
        et_password_new = (EditText) findViewById(R.id.setting_et_passwordNew);
        et_server_govId = (EditText) findViewById(R.id.setting_et_server_govId);
        et_service_password = (EditText) findViewById(R.id.setting_et_server_password);
        et_server_doctorId = (EditText) findViewById(R.id.setting_et_server_doctorId);
        et_hospitalName = (EditText) findViewById(R.id.setting_et_hospitalName);
        btn_edit = (Button) findViewById(R.id.setting_btn_edit);
        btn_login = (Button) findViewById(R.id.setting_btn_login);
        btn_setTime = (Button) findViewById(R.id.setting_btn_setTime);
        btn_updateJianhuyi = (Button) findViewById(R.id.setting_btn_updatejianhuyi);
        btn_updatejianhuyi_fromotg = (Button) findViewById(R.id.setting_btn_updatejianhuyi_fromotg);
        btn_setTime.setOnClickListener(listener);
        btn_updateJianhuyi.setOnClickListener(listener);
        btn_updatejianhuyi_fromotg.setOnClickListener(listener);
        btn_edit.setOnClickListener(listener);
        btn_login.setOnClickListener(listener);
        String name = SharedpreferenceUtil.getOffUserName(mContext, "admin");
        et_name.setText(name);
        et_name_new.setText(name);
        et_server_govId.setText(SharedpreferenceUtil.getToken(context, ""));
        et_service_password.setText(SharedpreferenceUtil.getOnPassword(context,
                ""));
        et_server_doctorId.setText(SharedpreferenceUtil.getOnDoctorId(mContext,
                ""));
        et_hospitalName.setText(SharedpreferenceUtil.getHospitalName(mContext,
                ""));
        et_serverAddress.setText(SharedpreferenceUtil.getserverAddress(mContext,
                ""));
        String pwd = SharedpreferenceUtil.getOffPassword(mContext, "123456");
        if ("123456".equals(pwd)) {
            et_password.setText("123456");
        }
        boolean useSannuo = SharedpreferenceUtil.getUseSannuo(context);
        if (useSannuo) {
            RadioButton setting_rb_xuetang_sannuo = (RadioButton) findViewById(R.id.setting_rb_xuetang_sannuo);
            setting_rb_xuetang_sannuo.setChecked(true);
        } else {
            RadioButton setting_rb_xuetang_kenuo = (RadioButton) findViewById(R.id.setting_rb_xuetang_kenuo);
            setting_rb_xuetang_kenuo.setChecked(true);
        }
    }

    private AlertDialog mUpdateXiaweijiDialog;
    private static final int ENABLED = 100301;
    protected static final int SETTING_SETTIMESUCCESS = 666;
    public static final int READER_DATA = 3;
    protected static final int LOGIN_STATE = 100302;
    protected static final int OFFLINE_STATE = 100303;
    protected static final int OFFLINE_STATE_OK = 100304;
    protected static final int OFFLINE_STATE_ERROR = 100305;
    private String xiaweiji_version = "";
    private byte[] xiaweiji_version_bytes = null;
    boolean checkxiaweijiUPdate = false;
    private Handler usbHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SETTING_SETTIMESUCCESS:
                    ToastTool.showLong(context, "时间设置成功!");
                    break;
                case READER_DATA:
                    String data = (String) msg.obj;
                    data = data.replaceAll(" ", "");
                    // ToastTool.showLong(context, "获取数据!" + data);
                    System.out.println("usb获取数据:" + data);
                    // 有V和.来判断是版本信息数据
                    if (data.contains("2E") && data.contains("56")) {
                        byte[] datas = StringUtils.HexToByteArr(data);
                        xiaweiji_version_bytes = datas;
                        // StringUtils.Byte2Hex(paramByte);
                        if (datas.length >= 9) {
                            char data0 = (char) datas[0];
                            char data1 = (char) datas[1];
                            char data2 = (char) datas[2];
                            char data3 = (char) datas[3];
                            char data4 = (char) datas[4];
                            char data5 = (char) datas[5];
                            char data6 = (char) datas[6];
                            char data7 = (char) datas[7];
                            char data8 = (char) datas[8];
                            String version = "" + data0 + data1 + data2 + data3
                                    + data4 + data5 + data6 + data7 + data8;
                            xiaweiji_version = version;
                            tv_jianhuyi_version
                                    .setText("监护仪版本:" + xiaweiji_version);
                            // 这里开始从服务器获取命令然后比对。
                            if (checkxiaweijiUPdate) {
                                checkXiaweijiUpdate();
                            }
                        }
                        return;
                    }

                    // 一共8个字节
                    // 563031312E3032 V0011.02&&http:
                    // 如果V001X 忽略X判断V001匹配，就判断流水号更新
                    // 如果V0011 则判断V0011全匹配后判断更新

                    // 监护仪返回开始升级的命令，准备就绪，开始向监护仪写入升级文件。
                    if ("EE35FF010155CC".equals(data)) {
                        // 开始升级。
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (beneCheckDevice != null
                                        && beneCheckDevice.isConnected()) {
                                    // 写入更新的命令。
                                    // ByteArrayInputStream
                                    try {
                                        File f = null;
                                        if (isFromOTG) {
                                            f = new File(
                                                    FileSaveUtil.getSDCardPath(),
                                                    fileName_xiaweijigujian);
                                        } else {
                                            f = new File(
                                                    FileSaveUtil.getSDCardPath(),
                                                    fileName_xiaweijigujian);
                                        }
                                        InputStream in;
                                        in = new FileInputStream(f);
                                        byte b[] = new byte[(int) f.length()]; // 创建合适文件大小的数组
                                        in.read(b); // 读取文件中的内容到b[]数组
                                        in.close();
                                        System.out.println(new String(b));
                                        beneCheckDevice.WriteData(b, b.length,
                                                20000);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                    }
                    if ("EE35FF000055CC".equals(data)) {
                        // 升级失败
                        if (mUpdateXiaweijiDialog != null
                                && mUpdateXiaweijiDialog.isShowing()) {
                            mUpdateXiaweijiDialog.dismiss();
                        }
                        mUpdateXiaweijiDialog = showDialog("提示", "监护仪升级失败!", true);
                        mUpdateXiaweijiDialog.show();
                        // ToastTool.showLong(context, "监护仪升级失败!");
                    }
                    if ("EE35FFFFFF55CC".equals(data)) {
                        // 升级成功
                        if (mUpdateXiaweijiDialog != null
                                && mUpdateXiaweijiDialog.isShowing()) {
                            mUpdateXiaweijiDialog.dismiss();
                        }
                        mUpdateXiaweijiDialog = showDialog("提示", "监护仪升级成功!", true);
                        mUpdateXiaweijiDialog.show();
                        // ToastTool.showLong(context, "监护仪升级成功!");
                    }
                    break;
                case 2:
                    // Toast.makeText(SettingActivity.this, "设备已断开！",
                    // Toast.LENGTH_SHORT).show();
                    if (mUpdateXiaweijiDialog != null
                            && mUpdateXiaweijiDialog.isShowing()) {
                        mUpdateXiaweijiDialog.dismiss();
                    }
                    mUpdateXiaweijiDialog = showDialog("提示", "警告，数据线已经拔掉！", true);
                    mUpdateXiaweijiDialog.show();
                    if (downloadTask != null) {
                        downloadTask.cancelDialog();
                    }
                    break;
                case 4:
                    Toast.makeText(SettingActivity.this, "设备打开失败！",
                            Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    // Toast.makeText(SettingActivity.this, "设备打开成功！",
                    // Toast.LENGTH_SHORT).show();
                    break;
                case 44:
                    dismissDialog();
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /***
     * 返回一个对象
     *
     * @param title
     * @param message
     * @return
     */
    protected AlertDialog showDialog(String title, String message, boolean setOK) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        if (setOK) {
            dialogBuilder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
        }
        dialogBuilder.setCancelable(false);
        dialogBuilder.setTitle(title).setMessage(message);
        AlertDialog dialog = dialogBuilder.create();
        return dialog;
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        private Context context;
        private PowerManager.WakeLock mWakeLock;
        ProgressDialog mProgressDialog;
        private String filePath;

        public void cancelDialog() {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            isCancel_uploadXiaweiji = true;
            if (!DownloadTask.this.isCancelled()) {
                DownloadTask.this.cancel(true);
            }
        }

        public DownloadTask(Context context) {
            this.context = context;
            // instantiate it within the onCreate method
            mProgressDialog = new ProgressDialog(SettingActivity.this);
            mProgressDialog.setMessage("正在下载升级包，请耐心等候!");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mProgressDialog.dismiss();
                            isCancel_uploadXiaweiji = true;
                            if (!DownloadTask.this.isCancelled()) {
                                DownloadTask.this.cancel(true);
                            }
                            // 发送消息取消对话框
                            mHandler.obtainMessage(what_showDialogCancle)
                                    .sendToTarget();
                        }
                    });
            mProgressDialog
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            if (!DownloadTask.this.isCancelled()) {
                                DownloadTask.this.cancel(true);
                            }
                        }
                    });
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                filePath = sUrl[1];
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return null;
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                // download the file
                input = connection.getInputStream();
                // 文件的路径
                File file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                }
                if (!file.exists()) {
                    file.createNewFile();
                }
                output = new FileOutputStream(filePath);
                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return null;
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }
                if (connection != null)
                    connection.disconnect();
            }
            return filePath;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context
                    .getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            mProgressDialog.dismiss();
            if (TextUtils.isEmpty(result)) {
                // Toast.makeText(context, "下载文件错误: " + result,
                // Toast.LENGTH_LONG)
                // .show();
                mHandler.obtainMessage(what_downxiaweiji_error).sendToTarget();
            } else {
                if (!isCancel_uploadXiaweiji
                        && result.contains(fileName_xiaweijigujian)) {
                    mHandler.obtainMessage(what_uploadXiaweiji).sendToTarget();
                    return;
                }
                if (!isCancel_uploadXiaweiji && result.contains("apk")) {
                    UpdateTool.openFile(new File(result), context);
                    mHandler.obtainMessage(what_showDialogCancle)
                            .sendToTarget();
                    Toast.makeText(context, "文件已经下载", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        boolean isStop = true;
        if (beneCheckDevice != null) {
            beneCheckDevice.onStop(isStop);
        }
        if (mUpdateXiaweijiDialog != null && mUpdateXiaweijiDialog.isShowing()) {
            mUpdateXiaweijiDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        if (beneCheckDevice != null) {
            if (beneCheckDevice.isConnected()) {
                beneCheckDevice.CloseDevice();
            }
        }
        super.onDestroy();
        checkxiaweijiUPdate = false;
    }

    private OnClickListener listener = new OnClickListener() {

        @SuppressWarnings("static-access")
        @Override
        public void onClick(View v) {
            if (v == btn_updateJianhuyi) {
                checkxiaweijiUPdate = true;
                isFromOTG = false;
                myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                if (beneCheckDevice == null) {
                    beneCheckDevice = new BeneCheckDeviceHB(myManager,
                            SettingActivity.this, ACTION_USB_PERMISSION,
                            usbHandler);
                }
                // 从本地sdcard卡获取更新文件，写入监护仪
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (beneCheckDevice != null
                                && beneCheckDevice.isConnected()) {
                            // 写入开始更新的命令。
                            // byte[] command = new byte[] { (byte) 0xEE, 0x35,
                            // (byte) 0xff, 0x55, (byte) 0xaa, 0X55,
                            // (byte) 0XCC };
                            // 查询版本号
                            byte[] command = new byte[]{(byte) 0xEE, 0x35,
                                    (byte) 0xf0, 0x00, (byte) 0x00, 0X55,
                                    (byte) 0XCC};
                            beneCheckDevice.WriteData(command, command.length,
                                    2000);
                            mHandler.obtainMessage(
                                    what_showDialog_updateXiaweiji)
                                    .sendToTarget();
                        }
                    }
                }).start();
            }
            if (v == btn_updatejianhuyi_fromotg) {
                /*
                 * readDeviceList(); if(true){ return; }
				 */
                isFromOTG = true;
                mUpdateXiaweijiDialog = showDialog("提示",
                        "正在升级下位机，请确保下位机电量充足，请耐心等待!\n请勿拔掉数据线，更新成功后重启下位机", true);
                mUpdateXiaweijiDialog.show();
                myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                if (beneCheckDevice == null) {
                    beneCheckDevice = new BeneCheckDeviceHB(myManager,
                            SettingActivity.this, ACTION_USB_PERMISSION,
                            usbHandler);
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (beneCheckDevice != null
                                && beneCheckDevice.isConnected()) {
                            // 写入开始更新的命令。
                            byte[] command = new byte[]{(byte) 0xEE, 0x35,
                                    (byte) 0xff, 0x55, (byte) 0xaa, 0X55,
                                    (byte) 0XCC};
                            beneCheckDevice.WriteData(command, command.length,
                                    2000);
                        }
                    }
                }).start();
            }
            if (v == btn_setTime) {
                // 设置监护仪时间
                final Calendar calendar = Calendar.getInstance();
                final int mYear = calendar.get(Calendar.YEAR); // 获取当前年份
                final int mMonth = calendar.get(Calendar.MONTH);// 获取当前月份
                final int mDay = calendar.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
                final int mHour = calendar.get(Calendar.HOUR_OF_DAY);// 获取当前的小时数
                final int mMinute = calendar.get(Calendar.MINUTE);// 获取当前的分钟数
                final int mSecond = calendar.get(Calendar.SECOND);// 获取当前的分钟数
                myManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                beneCheckDevice = new BeneCheckDeviceHB(myManager,
                        SettingActivity.this, ACTION_USB_PERMISSION, usbHandler);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (beneCheckDevice != null
                                && beneCheckDevice.isConnected()) {
                            byte[] yearAndMonth = new byte[]{
                                    (byte) 0xEE,
                                    0x35,
                                    (byte) 0xf1,
                                    (byte) (StringUtils
                                            .int2OneByte(mYear - 2000)),
                                    (byte) (mMonth + 1), 0X55, (byte) 0XCC};
                            byte[] dayAndHour = new byte[]{(byte) 0xEE, 0x35,
                                    (byte) 0xf2, StringUtils.int2OneByte(mDay),
                                    StringUtils.int2OneByte(mHour), 0X55,
                                    (byte) 0XCC};

                            byte[] minuteAndSecond = new byte[]{(byte) 0xEE,
                                    0x35, (byte) 0xf3,
                                    StringUtils.int2OneByte(mMinute),
                                    StringUtils.int2OneByte(mSecond), 0X55,
                                    (byte) 0XCC};
                            beneCheckDevice.WriteData(yearAndMonth,
                                    yearAndMonth.length, 2000);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            beneCheckDevice.WriteData(dayAndHour,
                                    dayAndHour.length, 2000);
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            beneCheckDevice.WriteData(minuteAndSecond,
                                    minuteAndSecond.length, 2000);
                            usbHandler.obtainMessage(SETTING_SETTIMESUCCESS)
                                    .sendToTarget();
                        }

                    }
                }).start();
            }
            if (v == btn_edit) {
                String name = et_name.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                String nameNew = et_name_new.getText().toString().trim();
                String passwordNew = et_password_new.getText().toString()
                        .trim();
                if (!name.equals(SharedpreferenceUtil.getOffUserName(mContext,
                        "admin"))) {
                    ToastTool.showShort(mContext, "本地账号不正确！");
                } else if (!password.equals(SharedpreferenceUtil
                        .getOffPassword(mContext, "123456"))) {
                    ToastTool.showShort(mContext, "本地密码不正确！");
                } else if (TextUtils.isEmpty(nameNew)
                        || TextUtils.isEmpty(passwordNew)) {
                    ToastTool.showShort(mContext, "新用户名或新密码不能为空！");
                } else {
                    SharedpreferenceUtil.setOffUserName(mContext, nameNew);
                    SharedpreferenceUtil.setOffPassword(mContext, passwordNew);
                    ToastTool.showShort(mContext, "修改成功，请牢记用户名和密码！");
                }
            } else if (v == btn_login) {
                String server_govId = et_server_govId.getText().toString()
                        .trim();
                String server_password = et_service_password.getText()
                        .toString().trim();
                String server_doctorId = et_server_doctorId.getText()
                        .toString().trim();
                String hospitalName = et_hospitalName.getText().toString()
                        .trim();
                String serverAddress = et_serverAddress.getText().toString()
                        .trim();
                //保存服务器地址
                SharedpreferenceUtil.setserverAddress(mContext, serverAddress);
                SharedpreferenceUtil.setOnDoctorId(mContext, server_doctorId);
                // SharedpreferenceUtil.setOnGovId(mContext, server_govId);
                SharedpreferenceUtil.setOnPassword(mContext, server_password);
                if (!TextUtils.isEmpty(hospitalName)) {
                    SharedpreferenceUtil
                            .setHospitalName(mContext, hospitalName);
                    ToastTool.showShort(mContext, "保存医院名称成功");
                } else if (TextUtils.isEmpty(server_govId)
                        || TextUtils.isEmpty(server_doctorId)) {
                    // ToastTool.showShort(mContext, "服务器账号或密码不能为空");
                }
                ToastTool.showShort(mContext, "正在登陆");
                if (Tools.isNetConnected(mContext)) {
                    MyApplication.setUserAndPas(server_govId, server_doctorId);
                    // 执行登录操作。
                    WebService.login(context, new StringCallback() {

                        @Override
                        public void onSuccess(String str, Call call,
                                              Response response) {
                            // ToastTool.showShort(mContext, "返回数据"+str);
                            System.out.println("返回json：" + str);

                            try {
                                JSONObject jo = new JSONObject(str);
                                JSONObject ss = jo.optJSONObject("data");
                                Data_loginReturn data = (Data_loginReturn) JsonUtil
                                        .JSONStrToObj(ss.toString(),
                                                Data_loginReturn.class);
                                List<Role> roles = data.getRole();
                                // 先清除map集合。然后存放角色id的列表。
                                mRoleMap.clear();
                                for (int i = 0; i < roles.size(); i++) {
                                    Role r = roles.get(i);
                                    String Manaunitid = r.getManaunitid();
                                    String ManaunitName = r.getManaunitname();
                                    String code = r.getRoleId();
                                    String token = r.getUrt();
                                    if ("01".equals(code)
                                            && !TextUtils.isEmpty(token)) {
                                        // if (!TextUtils.isEmpty(token)) {
                                        // SharedpreferenceUtil.setToken(context,
                                        // "440403105001@01");
                                        // SharedpreferenceUtil.setOnGovId(context,"440403105001");
                                        SharedpreferenceUtil.setToken(context,
                                                token);
                                        SharedpreferenceUtil.setOnGovId(
                                                context, Manaunitid);
                                        mRoleMap.put(token, ManaunitName);
                                        // 登录成功后设置机构码
                                        jsonHandler.obtainMessage(
                                                what_success_ok).sendToTarget();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonHandler.obtainMessage(what_failed)
                                        .sendToTarget();
                            }
                        }

                        @Override
                        public void onError(Call call1, Response response1,
                                            Exception exception) {
                            super.onError(call1, response1, exception);
                            jsonHandler.obtainMessage(what_error)
                                    .sendToTarget();
                        }
                    });
                    onResume();
                } else {
                    ToastTool.showShort(mContext, "当前无网络，请检查网络连接");
                    dismissDialog();
                }
            }
        }
    };

    private static final int what_success_ok = 65;
    private static final int what_failed = 77;
    private static final int what_error = 87;
    Handler jsonHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case what_success_ok:
                    // 开始设置那个信息。
                    // MyApplication.setUserLogin(true);
                    // jump2MainUi();
                    Iterator i = mRoleMap.entrySet().iterator();
                    String key;
                    String value;
                    sp_datas.clear();
                    while (i.hasNext()) {
                        Map.Entry entry = (Map.Entry) i.next();
                        value = entry.getValue().toString();
                        sp_datas.add(value);
                    }
                    mSp_adapter.notifyDataSetChanged();
                    break;
                case what_failed:
                    ToastTool.showLong(context, "登陆错误");
                    MyApplication.setUserLogin(false);
                    break;
                case what_error:
                    ToastTool.showLong(context, "访问出错，请检查网络或配置信息");
                    MyApplication.setUserLogin(false);
                    break;
            }
        }

        ;
    };

    private void jump2MainUi() {
        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}
